from functools import wraps
from flask import request, make_response
import jwt
from tool.config.config import get_config

SECRET_KEY = get_config("config.toml")["FILE_SYSTEM"]["JWT_SECRET_KEY"]  # 替换为你的密钥

def cookie_jwt_required(view_func):
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        token = request.cookies.get("token")
        if not token:
            return make_response("wrong login", 401)

        try:
            decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
            # 可将用户信息附加到 request 上，方便后续使用
            request.user = decoded
        except jwt.ExpiredSignatureError:
            return make_response("登录过期，请重新登录", 401)
        except jwt.InvalidTokenError:
            return make_response("无效 Token", 401)

        return view_func(*args, **kwargs)
    return wrapper
